package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.SqfwWorkorderService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.*;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwV2.enums.AuthenticRightEnum;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sqfwV2.service.baiyunqu.AuthenticRightExcelService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.trans.Trans;

import java.sql.*;
import java.time.ZoneId;
import java.util.*;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.createConvergePdfAndUpload;

/**
 * @program: dfxy-community
 * @description: 白云区12345确权服务实现
 * @author: LJT
 * @create: 2024-03-11 08:46
 **/
@IocBean(name = "BaiYunQu12345AuthForAdminService")
@Slf4j
public class BaiYunQu12345AuthForAdminServiceImpl extends AuthenticRightExcelService implements SqfwCustomForAdminCommonService {

    @Inject
    SysUserService sysUserService1;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysLogService sysLogService;

    @Inject("taskUpdateExecutor")
    private ThreadPoolExecutor taskUpdateExecutor;

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Pagination pagination = new Pagination();
        pagination.setList(new ArrayList<>());
        Integer countNum = getDataList(bean, false).size();
        if (countNum > 0) {
            pagination.setPageNo(bean.getPageNo());
            pagination.setPageSize(bean.getPageSize());
            pagination.setTotalCount(getDataList(bean, false).size());

            List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = getDataList(bean, true);
            if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
                List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
                Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
                sqfwCustomForAdminCommonVOList.forEach(source -> {
                    SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                    BeanUtil.copyProperties(source, target);
                    target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                    finalCommonVOList.add(target);
                });
                pagination.setList(finalCommonVOList);
            }
        }
        log.info("BaiYunQu12345AuthForAdminServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    public int delete(String id) {
        int num = 0;
        Sqfw_formSummary_new sqfwFormsummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormsummaryNew == null) {
            return num;
        }
        log.info("删除记录:{},{}", SecurityUtil.getUserId(), id);
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getSqfwId, "=", sqfwFormsummaryNew.getSqfwId());
        List<Sqfw_formSummary_new> sqfwIdList = sqfwFormsummaryNewService.query(cnd);

        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        if (!sqfwIdList.isEmpty()) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            CompletableFuture.runAsync(() -> {
                for (Sqfw_formSummary_new sqfwFormSummaryNew : sqfwIdList) {
                    batchDeleteDataNew(userId, sqfwFormSummaryNew);
                }
            }, executorService);
            executorService.shutdown();
        }
        return sqfwIdList.size();
    }

    @Override
    public int batchDelete(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        // 查询数据
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getId, "in", ids);
        List<Sqfw_formSummary_new> newList = sqfwFormsummaryNewService.query(cnd);
        if (newList.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        Set<String> sqfwIds = newList.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toSet());
        cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getSqfwId, "in", sqfwIds);
        List<Sqfw_formSummary_new> sqfwIdList = sqfwFormsummaryNewService.query(cnd);

        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        if (!newList.isEmpty()) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            CompletableFuture.runAsync(() -> {
                for (Sqfw_formSummary_new sqfwFormSummaryNew : newList) {
                    batchDeleteDataNew(userId, sqfwFormSummaryNew);
                }
            }, executorService);
            executorService.shutdown();
        }
        return sqfwIdList.size();
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        sqfwFormsummaryNew.setUpdateBy(SecurityUtil.getUserId());
        sqfwFormsummaryNew.setUpdateDate(new Date());
        return sqfwFormsummaryNewService.updateIgnoreNull(sqfwFormsummaryNew);
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            generateExcelUrlVO.setExcelUrl(AuthenticRightEnum.getBlankTemplate(Integer.valueOf(excelConfigList.get(0).getFileIdentity())));
        } else {
            if (StringUtils.isEmpty(bean.getType())) {
                throw new AppException(ResultCode.NOT_FOUND.getMsg());
            }
            // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
            if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
                List<Sqfw_formSummary_new> summaryNewList = getDataList(bean, false);
                if (summaryNewList.size() > 0) {
                    bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList()));
                } else {
                    return new ArrayList<GenerateExcelUrlVO>();
                }
            } else {
                Cnd cnd = Cnd.NEW();
                // 时间
                if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
                    cnd.and(Sqfw_formSummary_new::getFillDate, ">=", communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()));
                    cnd.and(Sqfw_formSummary_new::getFillDate, "<=", communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
                }
                cnd.and(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList());
                List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
                if (summaryNewList.size() > 0) {
                    bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList()));
                } else {
                    return new ArrayList<GenerateExcelUrlVO>();
                }
            }
            if (excelConfigList.get(0).getOnlyGenerateTemplateFlag() == true) {
                bean.setFormSummaryNewIdList(Collections.emptyList());
            }

            // 将重复数据去除
            SqfwCustomForAdminCommonVO requestDate = new SqfwCustomForAdminCommonVO();
            requestDate.setType(bean.getType());
            requestDate.setCaseType(AuthenticRightEnum.getName(Integer.valueOf(excelConfigList.get(0).getFileIdentity())));
            requestDate.setFormSummaryNewIdList(bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> finalDataList = getDataList(requestDate, false);
            requestDate.setFormSummaryNewIdList(finalDataList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));

            CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
            List<ExcelCreateConfig> excelCreateConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(String.valueOf(excelConfigList.get(0).getFileIdentity()));
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setFormSummaryIdList(requestDate.getFormSummaryNewIdList());
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            BeanUtil.copyProperties(super.createExcelForAdmin(paramForController).get(0), generateExcelUrlVO);
        }
        generateExcelUrlVOS.add(generateExcelUrlVO);
        return generateExcelUrlVOS;
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            generateWordAndPdfUrlVO.setPdfUrl(AuthenticRightEnum.getBlankTemplate(Integer.valueOf(excelConfigList.get(0).getFileIdentity())));
        } else {
            if (StringUtils.isEmpty(bean.getType())) {
                throw new AppException(ResultCode.NOT_FOUND.getMsg());
            }
            // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
            if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
                List<Sqfw_formSummary_new> summaryNewList = getDataList(bean, false);
                if (summaryNewList.size() > 0) {
                    bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getSqfwId).distinct().collect(Collectors.toList()));
                } else {
                    return new GenerateWordAndPdfUrlVO();
                }
            } else {
                Cnd cnd = Cnd.NEW();
                cnd.and(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList());
                List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
                if (summaryNewList.size() > 0) {
                    bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList()));
                } else {
                    return new GenerateWordAndPdfUrlVO();
                }
            }

            String fileName = null;
            String code = excelConfigList.get(0).getFileIdentity();
            if (AuthenticRightEnum.A.getCode() == Integer.valueOf(code)) {
                fileName = "案件确权-协调通知书";
            } else {
                fileName = StrUtil.format(AuthenticRightEnum.getFileName(Integer.valueOf(code)), "12345");
            }

            List<Sqfw_formSummary_new> formSummarys = sqfwFormsummaryNewService.query(Cnd.where(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList())
                    .and(Sqfw_formSummary_new::getType, "=", bean.getType())
                    .and("param_data->>'caseType'", "=", AuthenticRightEnum.getName(Integer.parseInt(excelConfigList.get(0).getFileIdentity())))
                    .desc(Sqfw_formSummary_new::getCreateDate));
            List<String> flowIds = formSummarys.stream().map(Sqfw_formSummary_new::getSqfwFlowId).distinct().collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(flowIds)) {
                List<Sqfw_completeflow> completeflows = sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "IN", flowIds)
                        .and(Sqfw_completeflow::getFileType, "IN", Arrays.asList("12345确权","12345回访"))
                        .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                        .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                if (ObjectUtil.isNotEmpty(completeflows)) {
                    List<String> pdfList = completeflows.stream().map(Sqfw_completeflow::getResourcePath).distinct().collect(Collectors.toList());
                    try {
                        String url = createConvergePdfAndUpload(pdfList, fileName);
                        generateWordAndPdfUrlVO.setPdfUrl(url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return generateWordAndPdfUrlVO;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    public String buildQueryCondNew(SqfwCustomForAdminCommonVO bean, Boolean countFlg) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();

        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        cri.getOrderBy().desc("fill_date");
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService1.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCommunity())) {
            criSql.andEquals(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup caseNumber = Cnd.exps(new Static("param_data->>'caseNumber' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup caseAddress = Cnd.exps(new Static("param_data->>'caseAddress' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup linkman = Cnd.exps(new Static("param_data->>'linkman' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("create_user_name like '%" + bean.getQueryAll() + "%'"));
            criSql.and(caseNumber.or(caseAddress).or(linkman).or(createUserName));
        }
        // 需要排除的数据
        criSql.andNotEquals("fill_date", CommonConstants.WASTE_CREATE_TIME);

        // 案件编号
        if (StringUtils.isNotBlank(bean.getCaseNumber())) {
            criSql.andLike("param_data->>'caseNumber'", bean.getCaseNumber());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween("fill_date",
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 回访地点
        if (StringUtils.isNotBlank(bean.getCaseAddress())) {
            criSql.andLike("param_data->>'caseAddress'", bean.getCaseAddress());
        }
        // 协调地址
        if (StringUtils.isNotBlank(bean.getArrivalAddress())) {
            criSql.andLike("param_data->>'arrivalAddress'", bean.getArrivalAddress());
        }
        // 参与部门
        if (StringUtils.isNotEmpty(bean.getCompetentDepartment())) {
            StringBuffer sb = new StringBuffer();
            sb.append("param_data->'competentDepartment' @> '[{\"name\": \"").append(bean.getCompetentDepartment()).append("\"}]'");
            criSql.and(Cnd.exps(new Static(sb.toString())));
        }
        // 负责人员
        if (StringUtils.isNotEmpty(bean.getLinkman())) {
            criSql.andLike("param_data->>'linkman'", bean.getLinkman());
        }
        // 检查类型
        if (StringUtils.isNotEmpty(bean.getCheckType())) {
            String[] types = bean.getCheckType().split(",");
            criSql.andInStrArray("param_data->>'caseType'", types);
        }
        // 检查去重
        if (ObjectUtil.isNotEmpty(bean.getFormSummaryNewIdList())) {
            criSql.andInStrList("sqfw_id", bean.getFormSummaryNewIdList());
        }
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT t2.id AS id, t2.sqfw_id AS sqfw_id, t2.sqfw_flow_id AS sqfw_flow_id, t2.unit_id AS unit_id, t2.create_date AS create_date, t2.create_by AS create_by, t2.update_date AS update_date, t2.update_by update_by, t2.create_user_name AS create_user_name, t2.create_user_phone AS create_user_phone, t2.update_user_name AS update_user_name, t2.update_user_phone AS update_user_phone, t2.type AS type, t2.unit_name AS unit_name, t2.fill_date AS fill_date, t2.province AS province, t2.city AS city, t2.district AS district, t2.county AS county, t2.community AS community, t2.issue_status AS issue_status, t2.check_status AS check_status, t2.param_data AS param_data, t2.shops_base_info_id AS shops_base_info_id FROM ( SELECT t1.* FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY sqfw_id ORDER BY create_date DESC) AS rn FROM shequ.\"sqfw_form_summary_new\" ) t1 WHERE t1.rn <= 1) t2 ");
        sb.append(cri.toString());
        if (countFlg) {
            Integer pageNo = bean.getPageNo();
            Integer pageSize = bean.getPageSize();
            if (1 == pageNo) {
                pageNo = 0;
            }
            if (pageNo > 1) {
                pageNo = (pageNo - 1) * pageSize;
            }
            if (0 != pageSize) {
                sb.append(" LIMIT ").append(pageSize).append(" OFFSET ").append(pageNo);
            }
        }
        return sb.toString();
    }

    private List<Sqfw_formSummary_new> getDataList(SqfwCustomForAdminCommonVO bean, Boolean countFlg) {
        SqfwCustomForAdminCommonVO finalResult = new SqfwCustomForAdminCommonVO();
        Sql sql = Sqls.create(buildQueryCondNew(bean, countFlg));
        log.info("BaiYunQu12345AuthForAdminServiceImpl-list-SQL: {}", sql.toString());
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                List<Sqfw_formSummary_new> sqfwFormSummaryList = new ArrayList<Sqfw_formSummary_new>();
                while (rs.next()) {
                    Sqfw_formSummary_new sqfwFormSummary = new Sqfw_formSummary_new();
                    for (int i = 0; i < columnCount; i++) {
                        sqfwFormSummary.setId(rs.getString("id"));
                        sqfwFormSummary.setSqfwId(rs.getString("sqfw_id"));
                        sqfwFormSummary.setSqfwFlowId(rs.getString("sqfw_flow_id"));
                        sqfwFormSummary.setCreateDate(rs.getTimestamp("create_date"));
                        sqfwFormSummary.setCreateBy(rs.getString("create_by"));
                        sqfwFormSummary.setUpdateDate(rs.getTimestamp("update_date"));
                        sqfwFormSummary.setUpdateBy(rs.getString("update_by"));
                        sqfwFormSummary.setCreateUserName(rs.getString("create_user_name"));
                        sqfwFormSummary.setCreateUserPhone(rs.getString("create_user_phone"));
                        sqfwFormSummary.setType(rs.getString("type"));
                        sqfwFormSummary.setFillDate(rs.getTimestamp("fill_date"));
                        sqfwFormSummary.setParamData(rs.getString("param_data"));
                    }
                    sqfwFormSummaryList.add(sqfwFormSummary);
                }
                return sqfwFormSummaryList;
            }
        });
        sqfwFormsummaryNewService.execute(sql);
        return sql.getList(Sqfw_formSummary_new.class);
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            List<Sqfw_formSummary_new> summaryNewList = getDataList(bean, false);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList()));
            } else {
                return new ArrayList<CheckDataForAdminVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            cnd.and(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList()));
            } else {
                return new ArrayList<CheckDataForAdminVO>();
            }
        }

        CheckDataForAdminVO checkDataForAdminVO = new CheckDataForAdminVO();
        CheckDataForAdminVO checkDataForAdminExcelVO = new CheckDataForAdminVO();
        List<CheckDataForAdminVO> checkDataForAdminVOList = new ArrayList<CheckDataForAdminVO>();
        String fileName = null;
        Integer code = AuthenticRightEnum.A.getCode();
        fileName = StrUtil.format(AuthenticRightEnum.getFileName(code), "");
        checkDataForAdminVO.setCreateConditionFlag(false);
        int a = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList())
                .and(Sqfw_formSummary_new::getType, "=", bean.getType())
                .and("param_data->>'caseType'", "=", AuthenticRightEnum.A.getName()));
        if (a > 0) {
            checkDataForAdminVO.setCreateConditionFlag(true);
        }
        checkDataForAdminVO.setFileName(fileName + ".pdf");
        checkDataForAdminVO.setFileIdentity("1");
        checkDataForAdminVOList.add(checkDataForAdminVO);
        //--------------------------------------------------
        checkDataForAdminVO = new CheckDataForAdminVO();
        checkDataForAdminExcelVO = new CheckDataForAdminVO();
        checkDataForAdminVO.setCreateConditionFlag(false);
        checkDataForAdminExcelVO.setCreateConditionFlag(false);
        int b = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList())
                .and(Sqfw_formSummary_new::getType, "=", bean.getType())
                .and("param_data->>'caseType'", "=", AuthenticRightEnum.B.getName()));
        if (b > 0) {
            checkDataForAdminVO.setCreateConditionFlag(true);
            checkDataForAdminExcelVO.setCreateConditionFlag(true);
        }
        code = AuthenticRightEnum.B.getCode();
        fileName = StrUtil.format(AuthenticRightEnum.getFileName(code), "12345");
        checkDataForAdminVO.setFileName(fileName + ".pdf");
        checkDataForAdminVO.setFileIdentity("2");
        checkDataForAdminVOList.add(checkDataForAdminVO);

        code = AuthenticRightEnum.E.getCode();
        fileName = StrUtil.format(AuthenticRightEnum.getFileName(code), "12345");
        checkDataForAdminExcelVO.setFileName(fileName + ".xlsx");
        checkDataForAdminExcelVO.setFileIdentity("5");
        checkDataForAdminVOList.add(checkDataForAdminExcelVO);
        //-------------------------------------------------
        checkDataForAdminVO = new CheckDataForAdminVO();
        checkDataForAdminExcelVO = new CheckDataForAdminVO();
        checkDataForAdminVO.setCreateConditionFlag(false);
        checkDataForAdminExcelVO.setCreateConditionFlag(false);
        int c = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId, "IN", bean.getFormSummaryNewIdList())
                .and(Sqfw_formSummary_new::getType, "=", bean.getType())
                .and("param_data->>'caseType'", "=", AuthenticRightEnum.C.getName()));
        if (c > 0) {
            checkDataForAdminVO.setCreateConditionFlag(true);
            checkDataForAdminExcelVO.setCreateConditionFlag(true);
        }
        code = AuthenticRightEnum.C.getCode();
        fileName = StrUtil.format(AuthenticRightEnum.getFileName(code), "12345");
        checkDataForAdminVO.setFileName(fileName + ".pdf");
        checkDataForAdminVO.setFileIdentity("3");
        checkDataForAdminVOList.add(checkDataForAdminVO);
        //-------------------------------------------------
        code = AuthenticRightEnum.D.getCode();
        fileName = StrUtil.format(AuthenticRightEnum.getFileName(code), "12345");
        checkDataForAdminExcelVO.setFileName(fileName + ".xlsx");
        checkDataForAdminExcelVO.setFileIdentity("4");
        checkDataForAdminVOList.add(checkDataForAdminExcelVO);
        return checkDataForAdminVOList;
    }

    @Override
    public void reGeneratePdf(String id) {

    }

    /**
     * 批量删除
     *
     * @param userId
     * @param data
     */
    @Aop(TransAop.READ_COMMITTED)
    private void batchDeleteDataNew(String userId, Sqfw_formSummary_new data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.customservice.DaYingLuSecurityForAdminServiceImpl.batchDeleteDataNew",
                "com.budwk.app.sqfw.controllers.admin.DaYingLuSecurityForAdminController.batchDelete");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }
}
